package com.tdzh.maimaiti.view;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.tdzh.maimaiti.R;
import com.tdzh.maimaiti.util.JSONBuilder;
import com.tdzh.maimaiti.util.UriAPI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AskFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AskFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AskFragment extends BaseFragment implements View.OnClickListener {


    // TODO: Rename and change types of parameters

    private Button submit;
    private EditText askText;
    private EditText detailsText;
    private Spinner mSortSpinner;
    private String mSort;

    private OnFragmentInteractionListener mListener;

    public AskFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_ask, container, false);
        submit = (Button)view.findViewById(R.id.submit);
        askText = (EditText) view.findViewById(R.id.titleText);
        detailsText = (EditText) view.findViewById(R.id.detailsText);
        mSortSpinner = (Spinner) view.findViewById(R.id.SortSpinner);
        mSort="";
        String[] mItems = getResources().getStringArray(R.array.sortName);
        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_spinner_item, mItems);
        mSortSpinner.setAdapter(mAdapter);

        mSortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mSort = parent.getItemAtPosition(position).toString();
                Toast.makeText(getActivity(), "你点击的是: " + mSort, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        submit.setOnClickListener(this);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        //Activity activity = this.getActivity();
        if (mListener != null) {
            String title = String.valueOf(askText.getText());
            String details = String.valueOf(detailsText.getText());
            if(title.equals("") ||  title.trim().equals("")){
                askText.setError("请填写标题");
                return;
            }
            else if(details.equals("") || details.trim().equals("")){
                detailsText.setError("请详细描述您的要求");
                return;
            }
            else if(mSort.equals("请选择分类")){
                Toast.makeText(this.getContext(),"请选择分类！",Toast.LENGTH_SHORT);
                return;
            }
           // System.out.println("submit a request");
            SharedPreferences user = getActivity().getSharedPreferences("account",0);
           // System.out.println("AskFragment user:" + user.getString("name", null));
            Map<String, String> map = new HashMap<String, String>();
            //map.put("fNum", "A");
            map.put("title", String.valueOf(askText.getText()));
            map.put("sort", mSort);
            map.put("details", String.valueOf(detailsText.getText()));
            map.put("requester", "13269338058");

            Bundle bundle = new Bundle();
            bundle.putString("fNum","A");

            System.out.println("提问 " + (new JSONObject(map)).toString());
            new AskTask().execute(new JSONObject(map));
            mListener.onFragmentInteraction(bundle, v);
            //mListener.onFragmentInteraction(bundle, v);
        }

    }

    private class AskTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] params) {

            String result = "";

            //请求数据
            HttpPost httpRequest = new HttpPost(UriAPI.HTTPAskQuestion);
            try {
                //创建参数
                byte[] data = new byte[2048];

                List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                nameValuePair.add(new BasicNameValuePair("request", params[0].toString()));
                System.out.println("向服务器发送问题-已启动 ");
                //对提交数据进行编码
                httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair
                        , HTTP.UTF_8));
                HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                //获取响应服务器的数据
                System.out.println("连接 " + httpResponse.getStatusLine().getStatusCode());
                if (httpResponse.getStatusLine().getStatusCode() == 200) {

                    //先把从服务端来的数据转化成字节数组
                    data = EntityUtils.toByteArray((HttpEntity) httpResponse.getEntity());
                    //再创建字节数组输入流对象
                    ByteArrayInputStream bais = new ByteArrayInputStream(data);
                    //绑定字节流和数据包装流
                    DataInputStream dis = new DataInputStream(bais);
                    //将字节数组中的数据还原成原来的各种数据类型，代码如下：
                    result = new String(dis.readUTF());
                    //inStream.close();
                    System.out.println("result " + result);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(Object o) {
            //super.onPostExecute(o);
            if(o.toString().equals("Success")){
                Toast.makeText(getActivity(), "求助成功", Toast.LENGTH_SHORT).show();
                getActivity().getSupportFragmentManager().popBackStack();
            }else {
                Toast.makeText(getActivity(), "发送失败", Toast.LENGTH_SHORT).show();
            }

        }
    }
}
